<?php

/** Copyright 2014 TinPhp Systems, Inc.
 * @author zhangxilian 2014-2-8
 * @package TinPhp
 */
//ini_set('memcache.hash_function','crc32');
//ini_set('memcache.hash_strategy','consistent');
require_once './include/Flexihash/init.php';

//require_once './conf/memcache.conf.php';
/** 多台Memcache服务器Flexihash分布式存储处理类 */
class TinMemcache {

    private static $hash = null;
    private static $connectPool = null;
    /** 是否启用压缩存储，默认false */
    const MEMCACHE_COMPRESSED = FALSE;

    public function __construct() {
        
    }
    /**
     * 设置Memcache缓存
     * @param string $key 缓存KEY名称
     * @param string $value 缓存数据
     * @param int $expired 有效时间(秒)，默认1800
     * @return bool 返回true、false
     * */
    public static function set($key, $value, $expired = NULL) {
        $cache = TinMemcache::getCache($key);
        if ($cache) {
            //echo '<br>create '.$key;
            return $cache->set($key, $value, TinMemcache :: MEMCACHE_COMPRESSED, $expired);
//			if (memcache_set($cache, $key, $value, false, $cachetime)) {
//				return true;
//			}
        }
        return false;
    }
    /** 根据缓存KEY获取Memcache缓存数据
	 * @param string $key 缓存KEY名称
	 * @return object 没有数据返回null
	 * */
    public static function get($key) {
        $cache = TinMemcache::getCache($key);
        //echo '<br> get '.$key;
        if ($cache) {
            return $cache->get($key);
            //return memcache_get($cache, $key);
        }
        return false;
    }
    /** 删除指定Key的Memcache值
     * @param string $key 缓存KEY名称 */
    public static function del($key) {
        $cache = TinMemcache::getCache($key);
        if ($cache) {
            return $cache->delete($key);
            //return memcache_delete($cache, $key);
        }
        return false;
    }
    /** 清空所有Memcache缓存 */
    public static function flush() {
        $cache = TinMemcache::getCache('flush');
        if ($cache) {
            return $cache->flush();
        } else {
            return FALSE;
        }
    }
    /** 获取Memcache服务器链接对象 */
    public static function getCache($key) {
        self::createCache();

        $nodes = self::$hash->lookupList($key, count(self::$connectPool));
        foreach ($nodes as $node) {
            $server = explode(':', $node);
            if (!self::$connectPool[$node]) {
                self::$connectPool[$node] = @ memcache_connect($server[0], $server[1]);
            }
            if (self::$connectPool[$node]) {
                $_memcache = self::$connectPool[$node];
                return $_memcache;
                //return memcache_delete(self::$connectPool[$node], $key);
            } else {
                self::NoticeErrServer($node);
            }
        }
        return false;
    }
    /** Flexihash创建Memcache服务器链接对象 
     * @deprecated 配置文件配置服务器列表为 ip地址1:端口|ip地址2:11211
     */
    private static function createCache() {
        self::$hash = new Flexihash();
        $memcacheServerArr = explode("|", CACHE_SERVER_ARR);
        $tt_server_pool = array();
        foreach ($memcacheServerArr as $servers) {
            if ($servers != '') {
                $sv = explode(":", trim($servers));
                $tt_server_pool[] = array("host" => $sv[0], "port" => $sv[1]);
            }
        }
        if (count($tt_server_pool) <= 0) {
            //发邮件通知
            $sendM = T::sysSendEmail("sontin@qq.com", "Memcache异常", "Memcache服务器全部失败");
            header('Content-type: text/html; charset=utf-8');
            echo "<h2>服务器维护，请稍后重试...</h2>".$sendM;
            exit();
        }
        self::addServers($tt_server_pool);
    }
    /** 添加Memcache服务器地址 
     * @param array $servers 服务器地址数组 
     * array(0=>array("host"=>ip地址,"port"=端口), 1=>array("host"=>ip地址,"port"=端口))
     */
    private static function addServers($servers) {
        foreach ($servers as $server) {
            $node = $server['host'] . ':' . $server['port'];
            self::$connectPool[$node] = false;
            $targets[] = $node;
        }
        self::$hash->addTargets($targets);
    }
    /** 移除异常的服务器,并且邮件通知，目前弃用
     * @param string $sv 服务器地址
     */
    private static function NoticeErrServer($sv = null) {
        if ($sv == null)
            return;
        T :: sysLog("Memcache Error " . $sv);

//		$url = './conf/site.conf.php';
//   		$html = file_get_contents($url);			
//		$regex ='/define\("CACHE_SERVER_ARR","(.*)"\);/i';
//		$matches = array();
//		preg_match_all($regex, $html, $matches);
//		
//		if($matches && $matches[1]){
//			$newSlist = str_replace($sv, "", $matches[1][0]);
//			$newHtml = str_replace($matches[0], 'define("CACHE_SERVER_ARR","'.$newSlist.'");', $html);
//		}
//		$file = fopen($url,"w");
//		fwrite($file,$newHtml);
//		fclose($file);
//		//发邮件通知
//		$sendM = Y::sysSendEmail("sontin@qq.com", "Memcache异常-世纪商城", "Memcache异常:".$sv);
    }

}

?>